package com.ssm.springboot.config;

import com.ssm.springboot.dao.TbPermissionDao;
import com.ssm.springboot.dao.TbUserDao;
import com.ssm.springboot.pojo.TbPermission;
import com.ssm.springboot.pojo.TbUser;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyShiro extends AuthorizingRealm {
    @Resource
    private TbUserDao tbUserDao;
    @Autowired
    private TbPermissionDao tbPermissionDao;
    //权限认证
    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String userName = (String) principalCollection.getPrimaryPrincipal();
        //通过用户名获取用户实例,需要拿到用户id
        TbUser tbUser = tbUserDao.findByUserName(userName);
        //通过用户id,获取用户所拥有的权限
        List<TbPermission> permissionList = tbPermissionDao.findPermissionByUserid(tbUser.getId());
        //对权限进行去重,
        Set<String> permissionName = new HashSet<>();
        //将权限名,封装在集合中
        for(TbPermission p:permissionList){
            permissionName.add(p.getPermissionName());
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //将该用户所拥有的权限告诉给shiro
        simpleAuthorizationInfo.addStringPermissions(permissionName);
        return simpleAuthorizationInfo;
    }
    //登录认证
    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken){
        String userName = (String) authenticationToken.getPrincipal();
        TbUser byUserName = tbUserDao.findByUserName(userName);
        //用户名,用户的正确密码,该类的名字
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName,byUserName.getUserPassword(), ByteSource.Util.bytes("ssm"),getName());
        return simpleAuthenticationInfo;
    }
}
